<template>
  <div class="activity-container">
    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <el-form :model="searchForm" label-width="120px" :inline="true">
        <el-form-item label="活动标题：">
          <el-input v-model="searchForm.titleFuzzy" placeholder="请输入活动标题" clearable />
        </el-form-item>
        <el-form-item label="地点：">
          <el-input v-model="searchForm.location" placeholder="请输入活动地点" clearable />
        </el-form-item>
        <el-form-item label="社团：">
          <el-select v-model="searchForm.clubId" placeholder="请选择社团" clearable :style="{ width: '220px' }">
            <el-option
                v-for="club in clubList"
                :key="club.id"
                :label="club.name"
                :value="club.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围：">
          <el-date-picker
              v-model="searchForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 活动列表 -->
    <div class="activity-list">
      <el-row :gutter="20">
        <el-col v-for="activity in activityList" :key="activity.id" :span="8">
          <el-card class="activity-item" shadow="hover">
            <div class="activity-image">
              <el-image 
                :src="activity.imageUrl"
                fit="fill"
                class="activity-cover"
                :preview-src-list="activity.imageUrl ? [activity.imageUrl] : []"
                :preview-teleported="true"
              />
            </div>
            <div class="activity-info">
              <h4 class="activity-title">{{ activity.title }}</h4>
              <div class="activity-description" :title="activity.description">
                {{ activity.description }}
              </div>
              <div class="activity-details">
                <div class="activity-location">
                  <span>地点: {{ activity.location }}</span>
                </div>
                <div class="activity-time">
                  <div>开始时间: {{ formatDateTime(activity.startTime) }}</div>
                  <div>结束时间: {{ formatDateTime(activity.endTime) }}</div>
                </div>
              </div>
            </div>
            <!-- 移动申请按钮到卡片底部 -->
            <div class="activity-actions">
              <el-button type="success" size="small" @click="openJoinDialog(activity)">
                申请
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑/新增对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px">
      <el-form 
        :model="activityForm" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="activityForm.title" />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input type="textarea" v-model="activityForm.description" rows="3" />
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <el-date-picker
            v-model="activityForm.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" />
        </el-form-item>
        <el-form-item label="活动图片" prop="image">
          <el-input v-model="activityForm.image" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 申请对话框 -->
    <el-dialog
      v-model="joinDialogVisible"
      title="申请参加活动"
      width="30%"
    >
      <p>您确定要申请参加 {{ selectedActivity?.title }} 吗？</p>
      <!-- 申请原因输入框 -->
      <el-form :model="joinForm" label-width="80px">
        <el-form-item label="申请原因">
          <el-input v-model="joinForm.applyContent" type="textarea" :rows="4" placeholder="请输入申请原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="joinDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="joinActivity">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import axios from 'axios'

const activityList = ref([])

const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const clubList = ref([]) // 新增：社团列表

const searchForm = reactive({
  titleFuzzy: '',
  location: '',
  timeRange: [],
  clubId: null // 新增：社团ID
})

const activityForm = reactive({
  id: null,
  title: '',
  description: '',
  time: [],
  location: '',
  image: '' // 新增：活动图片
})

const rules = {
  title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }],
  time: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
  image: [{ required: true, message: '请输入活动图片地址', trigger: 'blur' }] // 新增：活动图片验证规则
}

// 加载社团列表
const loadClubs = async () => {
  try {
    const res = await axios.get('/club/loadDataList')
    if (res.data.status === 'success') {
      clubList.value = res.data.data.list || []
    } else {
      ElMessage.error(res.data.info || '获取社团列表失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('获取社团列表失败')
  }
}

// 在加载活动列表时，初始化每个活动的 showFullDescription 属性
const loadActivities = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      titleFuzzy: searchForm.titleFuzzy,
      location: searchForm.location,
      clubId: searchForm.clubId
    }

    // 修改：将 timeRange 映射为 startTimeStart 和 startTimeEnd
    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.startTimeStart = searchForm.timeRange[0]
      params.startTimeEnd = searchForm.timeRange[1]
    }

    const res = await axios.get('/activity/loadDataList', {
      params
    })

    if (res.data.status === 'success') {
      activityList.value = res.data.data.list
      total.value = res.data.data.totalCount || 0
    } else {
      ElMessage.error(res.data.info || '获取活动列表失败')
      activityList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('获取活动列表失败')
    activityList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return dayjs(datetime).format('YYYY-MM-DD HH:mm')
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          ...activityForm,
          startTime: activityForm.time[0],
          endTime: activityForm.time[1]
        }
        delete data.time

        let res
        if (data.id) {
          res = await axios.post('/activity/updateActivityById', data)
        } else {
          res = await axios.post('/activity/add', data)
        }

        if (res.data.status === 'success') {
          ElMessage.success(data.id ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadActivities()
        } else {
          ElMessage.error(res.data.info || (data.id ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(activityForm.id ? '更新失败' : '添加失败')
      }
    }
  })
}

const handleSearch = () => {
  currentPage.value = 1
  loadActivities()
}

const resetSearch = () => {
  searchForm.titleFuzzy = ''
  searchForm.location = ''
  searchForm.timeRange = []
  searchForm.clubId = null
  currentPage.value = 1
  loadActivities()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadActivities()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadActivities()
}

const toggleDescription = (activity) => {
  activity.showFullDescription = !activity.showFullDescription
}

// 新增：弹窗显示控制
const joinDialogVisible = ref(false)
const selectedActivity = ref(null)

// 新增：申请表单
const joinForm = reactive({
  applyContent: ''
})

// 新增：打开申请弹窗的方法
const openJoinDialog = (activity) => {
  selectedActivity.value = activity
  joinForm.applyContent = '' // 清空申请原因
  joinDialogVisible.value = true
}

// 新增：申请活动的方法
const joinActivity = async () => {
  try {
    const res = await axios.post('/registration/join', {
      activityId: selectedActivity.value.id, // 确保 activityId 被正确传递
      applyContent: joinForm.applyContent // 确保 content 被正确传递
    }, {
      headers: {
        'Token': localStorage.getItem('token') // 添加请求头
      }
    })

    if (res.data.status === 'success') {
      ElMessage.success('申请成功')
      joinDialogVisible.value = false
    } else {
      ElMessage.error(res.data.info || '申请失败')
    }
  } catch (error) {
    console.error('申请活动失败:', error)
    ElMessage.error('申请失败')
  }
}

onMounted(() => {
  loadActivities()
  loadClubs() // 新增：加载社团列表
})
</script>

<style scoped>
.activity-container {
  padding: 20px;
}

.search-wrapper {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  margin-right: 10px;
  white-space: nowrap;
  font-weight: bold;
}

.btn-group {
  display: flex;
  gap: 10px;
}

.activity-list {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.activity-item {
  margin-bottom: 20px;
  transition: transform 0.2s;
}

.activity-item:hover {
  transform: translateY(-5px);
}

.activity-image {
  width: 100%;
  height: 160px;
  overflow: hidden;
  margin-bottom: 15px;
  border-radius: 8px;
}

.activity-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.activity-info {
  text-align: left;
  padding: 10px;
}

.activity-title {
  margin: 10px 0;
  font-size: 18px;
  color: #333;
}

.activity-description {
  color: #666;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.activity-details {
  display: flex;
  flex-direction: column;
  margin: 10px 0;
  color: #666;
}

.activity-details .activity-location {
  margin-bottom: 5px;
  font-weight: bold;
}

.activity-details .activity-time {
  font-size: 14px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 优化申请按钮样式和位置 */
.activity-actions {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
}

.activity-item .el-button {
  margin-top: 10px;
}

/* 弹窗样式 */
.el-dialog .el-form-item {
  margin-bottom: 20px;
}

.el-dialog .el-form-item__label {
  font-weight: bold;
}
</style>